#include "server.h"
#include "svr_util/include/read_cfg.h"
#include "inner_con.h"
#include "sol/sol.hpp"

using namespace std;
using namespace proto;
using namespace lc;

bool Server::Init()
{
	L_COND_F(m_cfg.Init());
	bool r = false;
	r = RpcNetSvr<InnerSvrCon>::Ins().Init(m_cfg.GetInnerPort(), m_cfg.GetInnerIp());
	L_COND_F(r);
	AccRpcSvr::Init();

	r = m_clientListener.Init(m_cfg.GetExPort(), m_cfg.GetExIp());
	L_COND_F(r);

	L_DEBUG("Server::Init ok");
	return true;
}

ExternalSvrCon * Server::FindExternalSvrCon(uint64 cid)
{
	SvrCon *pClient = m_clientListener.GetConnMgr().FindConn(cid);
	ExternalSvrCon *p = dynamic_cast<ExternalSvrCon *>(pClient);
	if (nullptr == p)
	{
		L_DEBUG("find ClientSvrCon fail. cid=%lld", cid);
	}
	return p;
}

uint32 Server::GetExConSize() const
{
	return m_clientListener.GetConstConnMgr().GetConSize();
}

bool CfgMgr::Init()
{
	sol::state lua;
	lua.open_libraries(sol::lib::base,
		sol::lib::package,
		sol::lib::table,
		sol::lib::string);
	sol::protected_function_result r = lua.do_file("access.lua");
	if (!r.valid())
	{
		sol::error err = r;
		std::string what = err.what();
		LERROR("zone.lua load fail error:", what);
		return false;
	}
	L_DEBUG("init cfg");

	m_inner_ip = lua["selAcc"]["innerIp"];
	L_DEBUG("inner_ip=%s", m_inner_ip.c_str());
	m_inner_port = lua["selAcc"]["innerPort"];
	L_DEBUG("inner_port=%d", m_inner_port);

	m_ex_ip = lua["selAcc"]["exIp"];
	L_DEBUG("ex_ip=%s", m_ex_ip.c_str());
	m_ex_port = lua["selAcc"]["exPort"];
	L_DEBUG("ex_port=%d", m_ex_port);

	max_send_buf_size = 0;
	return true;
}
